package com.irdstudio.efp.esb.api.rest.sed.ploaninfo;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.ESBConstant;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.efp.console.common.psd.PsdConstantSet;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.LoanInfArry;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.ReqPersonalLoanInfo;
import com.irdstudio.efp.esb.api.bean.sed.ploaninfo.RespPersonalLoanInfo;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.sed.PersonalLoanQryTypeEnum;
import com.irdstudio.efp.esb.api.service.sed.ploaninfo.PersonalLoanInfoService;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.vo.AccLoanStatisticalInfo;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;


/**
* 普税贷产品对税e贷产品的此部分代码做了复用
* 说明：为了保证功能的复用性、提升开发的工作效率，对该代码进行了复用
* 评估是否会影响线上功能：否
* 评估时间：2020/5/25
* 处理方案：保留复用
*/
/**
 * 需求编号：【2019D0519】
 * 问题编号：【】
 * 个人信息查询
 *
 * @author xiaojunhui
 * @version 0.1
 * @date 2019/5/20 16:57
 */
@RestController
@RequestMapping("/esb")
public class PersonalLoanInfoController implements FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(PersonalLoanInfoController.class);

    @Autowired
    @Qualifier("personalLoanInfoService")
    private PersonalLoanInfoService personalLoanInfoService;

    @Autowired
    @Qualifier("accLoanService")
    private AccLoanService accLoanService;

    @Autowired
    private PubSysInfoService pubSysInfoService;

    @Autowired
    private NlsApplyInfoService nlsApplyInfoService;

    /**
     * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("校验 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    /**
     * 获取ESB请求对象，校验 ESB请求体对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("reqPersonalLoanInfo")
    public ReqPersonalLoanInfo getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("校验 ESB请求体对象！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ReqPersonalLoanInfo.class, Feature.InternFieldNames);
    }

    /**
     * 处理请求
     *
     * @param esbReqServiceBean   esb请求对象
     * @param br1
     * @param reqPersonalLoanInfo 返回对象
     * @param br2
     * @param exception
     * @return
     */
    @PostMapping("/SERVICE_30230003_06")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated @ModelAttribute("reqPersonalLoanInfo") ReqPersonalLoanInfo reqPersonalLoanInfo, BindingResult br2, Exception exception) {
        String glblSrlNo = esbReqServiceBean.getSysHead().getGlblSrlNo();
        logger.info("借据信息查询开始,全局流水号为：[{}]",glblSrlNo);
        //查询类型
        String qryType = reqPersonalLoanInfo.getQryTp();
        //页码-当前查询第几页的数据
        String pageNo = reqPersonalLoanInfo.getPgNO();
        //每页显示条数
        String pageSize = reqPersonalLoanInfo.getPerPgRcrNum();

        //响应体
        RespPersonalLoanInfo respPersonalLoanInfo = new RespPersonalLoanInfo();

        if (Objects.nonNull(exception)) {
            //如果异常不为空，那么处理异常返回信息
            return personalLoanInfoService.getEsbRespServiceBean(esbReqServiceBean, exception, pageNo, pageSize, respPersonalLoanInfo, EsbRetCodeStandard.JKYDCSJYBTG);
        }

        try {

            String openDay = pubSysInfoService.getOpenday("1001");
            if (StringUtils.isEmpty(openDay)) {
                throw new Exception("获取openday为空");
            }

            //根据查询类型封装不同条件的查询参数
            AccLoanVO accLoanVO = personalLoanInfoService.transferQueryParams(qryType, reqPersonalLoanInfo);
            //添加普税贷产品编码
            accLoanVO.setPrdId(PsdConstantSet.prdId);
            //根据类型查询数据走不同的查询函数
            List<AccLoanVO> rtList = new ArrayList<AccLoanVO>();
            if (PersonalLoanQryTypeEnum.QUERY_TYPE_01.getValue().equals(qryType)) {
                AccLoanVO accLoanVOS = accLoanService.querySinglePersonlLoanInfo(accLoanVO);
                if (accLoanVOS != null) {
                    rtList.add(accLoanVOS);
                }
            } else {
                List<AccLoanVO> accLoanVOS = accLoanService.queryPersonlLoanInfo(accLoanVO);
                rtList = accLoanVOS;
            }
            Integer totalSize = rtList.size();

            //处理授信查询结果

            if (!PersonalLoanQryTypeEnum.QUERY_TYPE_07.getValue().equals(qryType)&&!PersonalLoanQryTypeEnum.QUERY_TYPE_03.getValue().equals(qryType)) {
                rtList = personalLoanInfoService.handleResultList(rtList, qryType, pageNo, pageSize);
            }

            Map<String, AccLoanStatisticalInfo> accLoanStatisticalInfoMap = new HashMap<>();

/*			if (!rtList.isEmpty()) {
				//查询需要统计的信息
				List<AccLoanStatisticalInfo> accLoanStatisticalInfos  = accLoanService.queryAccLoanStatisticalInfos(rtList.stream().map(a -> a.getBillNo()).collect(Collectors.toList()));
				if (accLoanStatisticalInfos != null && !accLoanStatisticalInfos.isEmpty()) {
					for (AccLoanStatisticalInfo accLoanStatisticalInfo : accLoanStatisticalInfos) {
						accLoanStatisticalInfoMap.put(accLoanStatisticalInfo.getBillNo(), accLoanStatisticalInfo);
					}
				}
			}*/
            ArrayList<LoanInfArry> loanInfArries = new ArrayList<>();
            for (int i = 0; i < rtList.size(); i++) {
                loanInfArries.add(i, personalLoanInfoService.getLoanInfArry(rtList.get(i), accLoanStatisticalInfoMap.get(rtList.get(i).getBillNo()), openDay,glblSrlNo));
            }
            if (PersonalLoanQryTypeEnum.QUERY_TYPE_07.getValue().equals(qryType)||PersonalLoanQryTypeEnum.QUERY_TYPE_03.getValue().equals(qryType)) {
                if (!loanInfArries.isEmpty()) {
                    //先过去出状态
                    loanInfArries = (ArrayList<LoanInfArry>) loanInfArries.stream().filter(a -> reqPersonalLoanInfo.getDblSt().equals(a.getDblSt())).collect(Collectors.toList());
                    totalSize = loanInfArries.size();
                    loanInfArries = (ArrayList<LoanInfArry>) personalLoanInfoService.handleResultList(loanInfArries, pageNo, pageSize);
                }
            }
            logger.info("借据信息查询接口---开始处理要返回的数据");
            personalLoanInfoService.setRespPersonalLoanInfo(pageNo, pageSize, respPersonalLoanInfo, totalSize, loanInfArries);
            logger.info("借据信息查询接口---数据处理结束");

            respPersonalLoanInfo.setRetStCd(ESBConstant.SUCCESS);
            respPersonalLoanInfo.setRetMsg("查询成功");
            //返回报文
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSONObject.toJSONString(respPersonalLoanInfo, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero),
                    EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(),
                    EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
                    "查询成功");
        } catch (BizException ex) {
            logger.error("借据信息查询接口出现异常，异常信息为：[{}]", ex.getMessage());
            ex.printStackTrace();
            return personalLoanInfoService.getEsbRespServiceBean(esbReqServiceBean, ex, pageNo, pageSize, respPersonalLoanInfo, EsbRetCodeStandard.JKYDCSJYBTG);
        } catch (Exception e) {
            logger.error("借据信息查询接口出现异常，异常信息为：[{}]", e.getMessage());
            e.printStackTrace();
            return personalLoanInfoService.getEsbRespServiceBean(esbReqServiceBean, e, pageNo, pageSize, respPersonalLoanInfo, EsbRetCodeStandard.SJCLYC);

        }
    }
}
